package com.controller;

import com.constants.Constants;
import com.entity.AllTask;
import com.tools.BaseUntil;
import com.tools.TaskListener;
import com.until.CreatePage;
import com.until.TaskManag;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

import java.applet.Applet;
import java.applet.AudioClip;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class MainController extends BaseUntil implements Initializable {
    @FXML
    private TableView tview;
    @FXML
    private TableView busytview;

    @FXML
    private TableColumn colTasktitle;
    @FXML
    private TableColumn colTaskinfo;
    @FXML
    private TableColumn colmaketime;
    @FXML
    private TableColumn colBusyTasktitle;
    @FXML
    private TableColumn colBusyTaskinfo;
    @FXML
    private TableColumn colbusymaketime;

    @FXML
    private Label timeclock;

    @FXML
    private CheckBox checkBoxTop;

    private String timeVar = "00:00:00";
    Timer timer = new Timer();

    static AllTask ditileTask = null;

    public static AllTask todoTask = new AllTask();

    public MainController() {
        //初始化时保存当前Controller实例
        Constants.controllers.put(this.getClass().getSimpleName(), this);
    }

    public void showList() {
        ObservableList<AllTask> list = FXCollections.observableArrayList();
        ObservableList<AllTask> busylist = FXCollections.observableArrayList();
        for (AllTask allTask : TaskListener.getAlltask()) {
            if (allTask.getTasktype().equals("计划任务")) {
                list.add(allTask);
            } else {
                busylist.add(allTask);
            }
        }
        colTasktitle.setCellValueFactory(new PropertyValueFactory("title"));//映射
        colTaskinfo.setCellValueFactory(new PropertyValueFactory("info"));
        colmaketime.setCellValueFactory(new PropertyValueFactory("maketime"));
        colBusyTasktitle.setCellValueFactory(new PropertyValueFactory("title"));//映射
        colBusyTaskinfo.setCellValueFactory(new PropertyValueFactory("info"));
        colbusymaketime.setCellValueFactory(new PropertyValueFactory("maketime"));
        System.out.println(list);
        tview.getItems().setAll(list); //tableview添加list
        busytview.getItems().setAll(busylist);
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        //设置置顶
        checkBoxTop.setSelected(false);
        //初始化计时器显示时间
        timer.scheduleAtFixedRate(timerTask, 0, 1000);
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            Date dateZero = sdf.parse("00:00:00");
            Date dataSet = sdf.parse("00:00:00");
            timenow.setTime(dataSet);
            timeZero.setTime(dateZero);
            timeclock.setText("00:00:00");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //查询已经有的数据进行展示
        showList();
    }


    public void addTask(ActionEvent actionEvent) throws IOException {
        CreatePage.getNew("newtask.fxml");
    }

    public void addbusyTask(ActionEvent actionEvent) throws IOException {
        CreatePage.getNew("newbusytask.fxml");
    }

    public void queryTask(ActionEvent actionEvent) throws IOException {
        CreatePage.getNew("query.fxml");
    }

    public void clearCache(ActionEvent actionEvent) {
        ObservableList<AllTask> list = FXCollections.observableArrayList();
        ObservableList<AllTask> busylist = FXCollections.observableArrayList();
        for (AllTask allTask : TaskListener.getAlltask()) {
            if (allTask.getTasktype().equals("计划任务")) {
                list.add(allTask);
            } else {
                busylist.add(allTask);
            }
        }
        colTasktitle.setCellValueFactory(new PropertyValueFactory("title"));//映射
        colTaskinfo.setCellValueFactory(new PropertyValueFactory("info"));
        colmaketime.setCellValueFactory(new PropertyValueFactory("maketime"));
        colBusyTasktitle.setCellValueFactory(new PropertyValueFactory("title"));//映射
        colBusyTaskinfo.setCellValueFactory(new PropertyValueFactory("info"));
        colbusymaketime.setCellValueFactory(new PropertyValueFactory("maketime"));
        //任何更新界面组件信息的代码
        tview.getItems().setAll(list); //tableview添加list
        busytview.getItems().setAll(busylist);
    }

    //************************************************
    boolean bPause = false;
    boolean bToggle = false;
    Calendar timenow = Calendar.getInstance();
    Calendar timeZero = Calendar.getInstance();

    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            if (bPause) {
                if (timenow.compareTo(timeZero) > 0) {
                    timenow.set(Calendar.SECOND, timenow.get(Calendar.SECOND) - 1);
                    if ((timenow.getTimeInMillis() - timeZero.getTimeInMillis()) <= 10000) {
                        flashText();
                    }
                } else {
                    if (todoTask.getTimeType().equals("zhuanzhu")) {
                        todoTask.setCountpotato(String.valueOf(Integer.valueOf(todoTask.getCountpotato()) + 1));
                    } else if (todoTask.getTimeType().equals("xiuxi")) {
                        todoTask.setCountsleep(String.valueOf(Integer.valueOf(todoTask.getCountsleep()) + 1));
                    }
                    TaskManag.updateTask(todoTask);
                    bPause = false;
                    try {
                        AudioClip p = Applet.newAudioClip(new URL(getClass().getClassLoader().getResource("1110.wav").toString()));
                        p.play();
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                }
                //display
                SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
                String dateString = formatter.format(timenow.getTime());
                /**
                 * 运行javaFX程序，系统会自动创建一个FX application thread线程，用于更新界面的组件信息，
                 * 例如ListView的items、Label的text。当我们想运用多线程实现业务，而自己创建的线程又直接导
                 * 致了界面组件信息的更新时，控制台就会抛出java.lang.IllegalStateException异常。
                 *  https://blog.csdn.net/int__double/article/details/89458911
                 * 假设在一个自己创建的线程中，调用了update()方法，update()方法用于更新主界面的组件信息，这会导致如题的异常
                 * 此时，可以如下调用update()方法
                 * Platform.runLater(()->{
                 *   update();
                 *    //任何更新界面组件信息的代码
                 * });
                 */
                Platform.runLater(() -> {
                    //任何更新界面组件信息的代码
                    timeclock.setText(dateString);
                });
            }
        }
    };

    private void flashText() {
        bToggle = !bToggle;
        if (bToggle) {
            //timeclock.setFont(Font.font("Agency FB", FontWeight.BOLD, 100));
        } else {
            //timeclock.setFont(Font.font("Agency FB", FontWeight.NORMAL, 100));
        }
    }

    //****************************************************
    public void clockRun(ActionEvent actionEvent) throws ParseException {
        if (!checkObjFieldIsNotNull(todoTask)) {
            message("请先点选要执行计时的任务");
            return;
        }
        if (!checkMessage("当前准备计时任务是:" + todoTask.getTitle() + "请确认..")) {
            return;
        }
        if (bPause) {
            if (!checkMessage("正在运行是否重启")) {
                return;
            }
        }
        timeVar = "00:25:00";
        //timeVar = "00:00:10";
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        Date dateZero = sdf.parse("00:00:00");
        Date dataSet = sdf.parse(timeVar);
        timenow.setTime(dataSet);
        timeZero.setTime(dateZero);
        timeclock.setText(timeVar);
        todoTask.setTimeType("zhuanzhu");
        bPause = true;
    }

    public void sleepRun(ActionEvent actionEvent) throws ParseException {
        if (!checkObjFieldIsNotNull(todoTask)) {
            message("请先点选要执行计时的任务");
            return;
        }
        if (!checkMessage("当前准备计时任务是:" + todoTask.getTitle() + "请确认..")) {
            return;
        }
        if (bPause) {
            if (!checkMessage("正在运行是否重启")) {
                return;
            }
        }
        timeVar = "00:05:00";
        //timeVar = "00:00:15";
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        Date dateZero = sdf.parse("00:00:00");
        Date dataSet = sdf.parse(timeVar);
        timenow.setTime(dataSet);
        timeZero.setTime(dateZero);
        timeclock.setText(timeVar);
        todoTask.setTimeType("xiuxi");
        bPause = true;
    }


    public void timeStop(ActionEvent actionEvent) throws ParseException {
        if (bPause) {
            if (!checkMessage("确定终止本次计时？")) {
                return;
            }
        }
        timeVar = "00:00:00";
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        Date dateZero = sdf.parse("00:00:00");
        Date dataSet = sdf.parse(timeVar);
        timenow.setTime(dataSet);
        timeZero.setTime(dateZero);
        timeclock.setText(timeVar);
        bPause = false;
    }

    /**
     * 选择是否置顶显示
     *
     * @param actionEvent
     */
    public void changeUpTop(ActionEvent actionEvent) {
        Stage stage = (Stage) checkBoxTop.getScene().getWindow();
        if (checkBoxTop.isSelected()) {
            stage.setAlwaysOnTop(true);
        } else {
            stage.setAlwaysOnTop(false);
        }
    }

    public void ClickTwo(MouseEvent event) throws IOException {
        if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
            Node node = ((Node) event.getTarget()).getParent();
            TableRow row;
            if (node instanceof TableRow) {
                row = (TableRow) node;
            } else if (node.getParent() instanceof javafx.scene.layout.AnchorPane) {
                row = null;
            } else if (node.getParent() instanceof javafx.scene.layout.StackPane) {
                row = null;
            } else {
                // clicking on text part
                row = (TableRow) node.getParent();
            }
            if(!checkObjFieldIsNotNull(row)){
                message("请点选数据");
                return;
            }
            if(!checkObjFieldIsNotNull(row.getItem())){
                message("请点选数据");
                return;
            }
            ditileTask = new AllTask();
            ditileTask = (AllTask) row.getItem();
            CreatePage.getNew("taskDitile.fxml");
        } else if (event.isPrimaryButtonDown() && event.getClickCount() == 1) {
            Node node = ((Node) event.getTarget()).getParent();
            TableRow row;
            if (node instanceof TableRow) {
                row = (TableRow) node;
                todoTask = (AllTask) row.getItem();
            } else if (node instanceof StackPane) {

            } else if (node.getParent() instanceof javafx.scene.layout.AnchorPane) {

            } else if (node.getParent() instanceof javafx.scene.layout.StackPane) {

            } else {
                // clicking on text part
                row = (TableRow) node.getParent();
                todoTask = (AllTask) row.getItem();
            }
        }
    }
}
